package com.sduept.nwld.mobile.rest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.document.entity.core.RecordAttachment;
import com.sduept.bigdata.document.services.RecordAttachmentManager;
import com.sduept.bigdata.web.core.manager.NoticeManager;
import com.sduept.bigdata.web.core.model.NoticeAnnouncement;
import com.sduept.nwld.mobile.manager.MobileUserInfoManager;
import com.sduept.nwld.mobile.manager.MobileUtil;
import com.sduept.permission.entity.DepartmentEntityBean;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.manager.DepartManager;
import com.sduept.permission.manager.PersonnelManager;
import com.sduept.utils.Base64;
import com.sduept.utils.DateUtil;
import com.sduept.utils.ZipUtil;

/**
 * 客户端通知公告模块rest
 * 
 *
 */
@RestController
@RequestMapping("/noticeService/")
public class NoticeService {
	@Autowired
	private NoticeManager nm;
	@Autowired
	private MobileUserInfoManager mu;
	@Autowired
	private RecordAttachmentManager ra;
	@Autowired
	private PersonnelManager pm;
	@Autowired
	private DepartManager dm;
	@Autowired
	private CommonDocumentProperties pros;
	//SQL注入检测类
	@Inject
	private MobileUtil mobileUtil;
	/**
	 * 根据app账户获取通知公告数目
	 * 
	 * @return
	 * */

	@GetMapping("/getNoticeCountByUserAccount/{account}")
	public String getNoticeCountByUserAccount(@PathVariable("account") String account) {
		try {
			account = mobileUtil.SQLInjectCheck(account);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		//PersonnelConfigure person=mu.findUserByAccount(account);
		PersonnelEntityBean person = pm.findPersonnelByCode(account);
		int result=0;
		if(null!=person) {
			List<NoticeAnnouncement> notices=nm.getNoticesByUserAndRange(person.getCode(),null, null);
			result=notices.size();
		}
		return String.valueOf(result);
	}
	/**
	 * 根据app账户获取通知公告，按发布时间降序排列
	 * 
	 * @return
	 * */

	@GetMapping("/getNoticeByUserAccount/{account}/{rangeStart}/{rangeEnd}")
	public String getNoticeByUserAccount(@PathVariable("account") String account,@PathVariable("rangeStart") int rangeStart,@PathVariable("rangeEnd") int rangeEnd) {
		try {
			account = mobileUtil.SQLInjectCheck(account);
			rangeStart = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(rangeStart)));
			rangeEnd = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(rangeEnd)));
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		//PersonnelConfigure person=mu.findUserByAccount(account);
		PersonnelEntityBean person = pm.findPersonnelByCode(account);
		String result="";
		if(null!=person) {
			List<NoticeAnnouncement> notices=nm.getNoticesByUserAndRange(person.getCode(),null, new int[]{rangeStart,rangeEnd});
			result=JSONArray.toJSONString(notices);
		}
		return result;
	}
	/**
	 * 根据id获取通知公告以及对应的附件列表
	 * 
	 * @return
	 * */

	@GetMapping("/getNoticeById/{noticeId}")
	public String getNoticeById(@PathVariable("noticeId") String noticeId) {
		try {
			noticeId = mobileUtil.SQLInjectCheck(noticeId);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		JSONObject jso=new JSONObject();
		NoticeAnnouncement na=nm.getNoticeById(noticeId);
		if(null!=na) {
			List<RecordAttachment> attachments=ra.getAttachmentsByOId(noticeId);
			jso.put("notice", na);
			jso.put("attach", attachments);
		}
		return jso.toJSONString();
	}
	/**
	 * 根据发布时间,有效期以及标题模糊检索已发布的通知公告
	 * 
	 * @return
	 * */

	@GetMapping("/getNoticeByDateAndTitle/{param}")
	public String getNoticeByDateAndTitle(@PathVariable("param") String param) {
		List<NoticeAnnouncement> notices=new ArrayList<>();
		JSONObject jso=JSONObject.parseObject(param);
		String sPublishTime=jso.getString("sPublishDate");
		String ePublishTime=jso.getString("ePublishDate");
		String sValidTime=jso.getString("sValidDate");
		String eValidTime=jso.getString("eValidDate");
		String title=jso.getString("title");
		String userAccount=jso.getString("userAccount");
		try {
			sPublishTime = mobileUtil.SQLInjectCheck(sPublishTime);
			ePublishTime = mobileUtil.SQLInjectCheck(ePublishTime);
			sValidTime = mobileUtil.SQLInjectCheck(sValidTime);
			eValidTime = mobileUtil.SQLInjectCheck(eValidTime);
			title = mobileUtil.SQLInjectCheck(title);
			userAccount = mobileUtil.SQLInjectCheck(userAccount);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		//PersonnelConfigure person=mu.findUserByAccount(userAccount);
		PersonnelEntityBean person = pm.findPersonnelByCode(userAccount);
		if(null!=person) {
			List<String> departNames=getDepartByAppAccount(person);
			Date sPublishDate="".equals(sPublishTime)?null:DateUtil.getDateByString(sPublishTime+" 00:00:00", DateUtil.pattern_ymdhms);
			Date ePublishDate="".equals(ePublishTime)?null:DateUtil.getDateByString(ePublishTime+" 23:59:59", DateUtil.pattern_ymdhms);
			Date sValidDate="".equals(sValidTime)?null:DateUtil.getDateByString(sValidTime+" 00:00:00", DateUtil.pattern_ymdhms);
			Date eValidDate="".equals(eValidTime)?null:DateUtil.getDateByString(eValidTime+" 23:59:59", DateUtil.pattern_ymdhms);
			notices=nm.getPublishNoticesByCondition(sPublishDate, ePublishDate,sValidDate,eValidDate,title,person.getCode(),departNames);
		}
		return JSONArray.toJSONString(notices);
	}
	/**
	 * 获取登录人所在的组织机构以及上层所有的机构
	 */
	private List<String> getDepartByAppAccount(PersonnelEntityBean person) {
		List<String> departNames=new ArrayList<>();
		if(null!=person) {
			List<DepartmentEntityBean> departs=dm.recursiveFindParentDepartments(person);
			departNames.add("全网");
			for(DepartmentEntityBean d:departs) {
				departNames.add(d.getName());
			}
		}
		return departNames;
	}
	/**
	 * 压缩并下载通知公告附件
	 * 
	 * @return
	 * */

	@GetMapping("/downloadFileZip/{fileId}")
	public String downloadFileZip(@PathVariable("fileId") String fileId) {
		try {
			fileId = mobileUtil.SQLInjectCheck(fileId);
		} catch (Exception e1) {
			e1.printStackTrace();
			return "查找文件失败，无法下载";
		}
		String res = null;
		if (!"null".equals(fileId)) {
			RecordAttachment rd = ra.getAttachmentById(fileId);
			if (rd != null) {// id在数据库中有
				String filePath = pros.getExportTempPath() + rd.getPath();
				List<File> fileList = new ArrayList<File>();
				File docFile = new File(filePath);
				fileList.add(docFile);
				String tmpZipPath = pros.getExportTempPath() + rd.getId() + ".zip";
				ZipUtil.zipFile(tmpZipPath, fileList);
				try {
					res = Base64.encodeFromFile(tmpZipPath);
			    	ZipUtil.deletefile(tmpZipPath);//删除zip
			    	rd.setDownloadCount(rd.getDownloadCount()+1);//下载次数加1
			    	ra.createOrUpdateRecordAttachment(rd);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				res = "查找文件失败，无法下载";
			}
		}
		return res;
	}
}
